import React, { useState } from 'react';
import { Modal, Upload, Button, message, Progress, Alert, Table, Typography, Space, Divider } from 'antd';
import { InboxOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { batchImportTexts, downloadImportTemplate } from '@/services/learningContentApi';

const { Dragger } = Upload;
const { Text, Link } = Typography;

interface ImportModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const ImportModal: React.FC<ImportModalProps> = ({ visible, onCancel, onSuccess }) => {
  const [uploading, setUploading] = useState(false);
  const [importProgress, setImportProgress] = useState(0);
  const [importResult, setImportResult] = useState<any>(null);
  const [fileList, setFileList] = useState<any[]>([]);

  // 处理文件上传
  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择要上传的文件');
      return;
    }

    const file = fileList[0];
    setUploading(true);
    setImportProgress(0);

    try {
      const formData = new FormData();
      formData.append('file', file);

      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setImportProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 200);

      const response = await batchImportTexts(formData);
      
      clearInterval(progressInterval);
      setImportProgress(100);
      setImportResult(response.data);
      
      if (response.data.success_count > 0) {
        message.success(`成功导入 ${response.data.success_count} 条文本`);
      }
      
      if (response.data.error_count > 0) {
        message.warning(`${response.data.error_count} 条文本导入失败`);
      }

    } catch (error) {
      message.error('文件上传失败');
      setImportProgress(0);
    } finally {
      setUploading(false);
    }
  };

  // 下载模板
  const handleDownloadTemplate = async () => {
    try {
      const blob = await downloadImportTemplate();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '检测文本导入模板.xlsx';
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      message.success('模板下载成功');
    } catch (error) {
      message.error('模板下载失败');
    }
  };

  // 重置状态
  const handleReset = () => {
    setFileList([]);
    setImportProgress(0);
    setImportResult(null);
  };

  // 完成导入
  const handleComplete = () => {
    if (importResult?.success_count > 0) {
      onSuccess();
    } else {
      onCancel();
    }
    handleReset();
  };

  // 错误信息表格列
  const errorColumns = [
    {
      title: '行号',
      dataIndex: 'row',
      width: 80,
    },
    {
      title: '文本内容',
      dataIndex: 'content',
      ellipsis: true,
    },
    {
      title: '错误原因',
      dataIndex: 'error',
      render: (error: string) => <Text type="danger">{error}</Text>,
    },
  ];

  return (
    <Modal
      title="批量导入检测文本"
      open={visible}
      onCancel={() => {
        onCancel();
        handleReset();
      }}
      footer={[
        <Button key="cancel" onClick={() => {
          onCancel();
          handleReset();
        }}>
          取消
        </Button>,
        importResult ? (
          <Button key="complete" type="primary" onClick={handleComplete}>
            完成
          </Button>
        ) : (
          <Button
            key="upload"
            type="primary"
            loading={uploading}
            onClick={handleUpload}
            disabled={fileList.length === 0}
          >
            开始导入
          </Button>
        ),
      ]}
      width={800}
      destroyOnClose
    >
      <div>
        {/* 使用说明 */}
        <Alert
          message="导入说明"
          description={
            <div>
              <p>1. 请先下载导入模板，按照模板格式填写数据</p>
              <p>2. 支持 Excel (.xlsx) 格式文件</p>
              <p>3. 单次最多导入 1000 条文本</p>
              <p>4. 文本内容不能为空，长度不超过 500 字符</p>
              <p>5. 难度等级：easy(简单)、medium(中等)、hard(困难)</p>
              <p>6. 分类：daily(日常)、business(商务)、academic(学术)、poetry(诗词)、idiom(成语)</p>
            </div>
          }
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        {/* 下载模板 */}
        <div style={{ marginBottom: 24, textAlign: 'center' }}>
          <Button
            icon={<DownloadOutlined />}
            onClick={handleDownloadTemplate}
            size="large"
          >
            下载导入模板
          </Button>
        </div>

        <Divider />

        {/* 文件上传 */}
        {!importResult && (
          <Dragger
            fileList={fileList}
            beforeUpload={(file) => {
              const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
              if (!isExcel) {
                message.error('只能上传 Excel 文件！');
                return false;
              }
              const isLt10M = file.size / 1024 / 1024 < 10;
              if (!isLt10M) {
                message.error('文件大小不能超过 10MB！');
                return false;
              }
              setFileList([file]);
              return false;
            }}
            onRemove={() => {
              setFileList([]);
            }}
            multiple={false}
            accept=".xlsx"
          >
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p className="ant-upload-hint">
              支持 Excel (.xlsx) 格式，文件大小不超过 10MB
            </p>
          </Dragger>
        )}

        {/* 导入进度 */}
        {uploading && (
          <div style={{ marginTop: 24 }}>
            <div style={{ marginBottom: 8 }}>导入进度</div>
            <Progress percent={importProgress} status="active" />
          </div>
        )}

        {/* 导入结果 */}
        {importResult && (
          <div style={{ marginTop: 24 }}>
            <Alert
              message="导入完成"
              description={
                <div>
                  <p>总计处理: {importResult.total_count} 条</p>
                  <p>成功导入: <Text type="success">{importResult.success_count}</Text> 条</p>
                  <p>导入失败: <Text type="danger">{importResult.error_count}</Text> 条</p>
                </div>
              }
              type={importResult.error_count > 0 ? 'warning' : 'success'}
              showIcon
              style={{ marginBottom: 16 }}
            />

            {/* 错误详情 */}
            {importResult.errors && importResult.errors.length > 0 && (
              <div>
                <div style={{ marginBottom: 12, fontWeight: 500 }}>错误详情：</div>
                <Table
                  columns={errorColumns}
                  dataSource={importResult.errors}
                  rowKey="row"
                  size="small"
                  pagination={{
                    pageSize: 5,
                    showSizeChanger: false,
                  }}
                  scroll={{ y: 200 }}
                />
              </div>
            )}
          </div>
        )}
      </div>
    </Modal>
  );
};

export default ImportModal;
